<!--
  * 操作日志表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 07:38:15
-->
<template>
  <!---------- 查询表单form begin ----------->

  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="输入查询" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.contentLike" placeholder="内容信息" />
      </a-form-item>
      <a-form-item label="操作类型" class="smart-query-form-item">
        <a-select v-model:value="queryForm.operType" style="width: 200px" placeholder="请选择">
          <a-select-option v-for="item in OPER_TYPE" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
        <!-- <SmartEnumSelect width="200px" v-model:value="queryForm.operType" enumName="ZZB_ENABLE_STATUS_ENUM" placeholder="请选择" /> -->
      </a-form-item>
      <!-- <a-form-item label="创建时间" class="smart-query-form-item">
        <a-range-picker v-model:value="queryForm.uTime" :presets="defaultTimeRanges" style="width: 220px" @change="onChangeCreateTime" />
      </a-form-item> -->

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>

          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
        <a-button class="smart-margin-left20" @click="moreQueryConditionFlag = !moreQueryConditionFlag">
          <template #icon>
            <MoreOutlined />
          </template>
          {{ moreQueryConditionFlag ? '收起' : '展开' }}
        </a-button>
      </a-form-item>
    </a-row>

    <a-row class="smart-query-form-row" v-show="moreQueryConditionFlag">
      <!-- <a-form-item label="终端类型" class="smart-query-form-item">
        <a-select v-model:value="queryForm.operDeviceType" style="width: 200px" placeholder="请选择">
          <a-select-option v-for="item in OPER_DEVICE_TYPE" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item> -->
      <a-form-item label="操作人员" class="smart-query-form-item">
        <CustomSelect
          v-model:value="queryForm.userId"
          :placeholder="'请选择姓名'"
          style="width: 200px"
          :api="userApi.page"
          :queryParams="userParams"
          queryParamKey="nameLeftLike"
          :response-adapter="filterUserParams"
          labelField="name,no"
        />
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block"></div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ text, record, column }">
        <!-- 有图片预览时 注释解开并把下面的'picture'修改成自己的图片字段名即可 -->
        <!-- <template v-if="column.dataIndex === 'picture'">
            <FilePreview :fileList="text" type="picture" />
          </template> -->

        <!-- 使用字典时 注释解开并把下面的'data-dictionaries'修改成自己的字典字段名即可 有多个字典字段就复制多份同理修改 不然不显示字典 -->
        <!-- 方便修改tag的颜色 orange green purple success processing error default warning -->
        <!-- <template v-if="column.dataIndex === 'data-dictionaries'">
          <a-tag color="cyan">
            {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
          </a-tag>
        </template> -->
        <template v-if="column.dataIndex === 'content'">
          {{ getContentValue(record.content) }}
        </template>
        <template v-else-if="column.dataIndex === 'contentDesc'">
          {{ getAttributeValue(record.content, 'contentDesc') }}
        </template>
        <template v-else-if="column.dataIndex === 'oldContent'">
          {{ getAttributeValue(record.content, 'oldContent') }}
        </template>
        <template v-else-if="column.dataIndex === 'newContent'">
          {{ getAttributeValue(record.content, 'newContent') }}
        </template>
        <template v-else-if="column.dataIndex === 'compareContent'">
          {{ getAttributeValue(record.content, 'compareContent') }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate"></div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>
</template>
<script setup>
  import { onMounted, reactive, ref, getCurrentInstance } from 'vue'
  import { operLogApi } from '/src/api/system/b-merchant/oper-log-api'
  import { PAGE_SIZE_OPTIONS } from '/src/constants/common-const'
  import { smartSentry } from '/src/lib/smart-sentry'
  import TableOperator from '/src/components/support/table-operator/index.vue'
  import SmartEnumSelect from '/src/components/framework/smart-enum-select/index.vue'
  import { defaultTimeRanges } from '/src/lib/default-time-ranges.js'
  import dayjs from 'dayjs'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { userApi } from '/@/api/system/b-merchant/user-api.js'
  import { ZZB_ENABLE_STATUS_ENUM } from '/@/constants/system/system-const.js'
  import { selectDictLabel } from '/@/utils/common'
  import {
    OPER_TYPE, //操作类型
    OPER_DEVICE_TYPE, // 终端设备
  } from '/@/constants/dict'
  const { proxy } = getCurrentInstance()

  //import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '日志时间',
      dataIndex: 'uTime',
      ellipsis: true,
      key: 'uTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD'),
      width: 180,
    },
    {
      title: '终端设备(数据字典)',
      dataIndex: 'operDeviceType',
      customRender: ({ text }) => {
        return selectDictLabel(OPER_DEVICE_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '操作类型(数据字典)',
      dataIndex: 'operType',
      customRender: ({ text }) => {
        return selectDictLabel(OPER_TYPE, text)
        // return selectDictLabel(proxy.$smartEnumPlugin.getValueDescList('ZZB_ENABLE_STATUS_ENUM'), text)
      },
      ellipsis: true,
    },
    {
      title: '操作人员',
      dataIndex: 'userName',
      ellipsis: true,
    },
    {
      title: 'ip地址',
      dataIndex: 'ip',
      ellipsis: true,
    },
    {
      title: '操作内容',
      dataIndex: 'contentDesc',
      ellipsis: true,
    },
    {
      title: '原数据',
      dataIndex: 'oldContent',
      ellipsis: true,
    },
    {
      title: '新数据',
      dataIndex: 'newContent',
      ellipsis: true,
    },
    {
      title: '差异数据',
      dataIndex: 'compareContent',
      ellipsis: true,
    },
  ])

  const getAttributeValue = (contentStr, attribute) => {
    try {
      const obj = JSON.parse(contentStr)
      return obj[attribute] || '暂无'
    } catch (error) {
      return '非 JSON 数据'
    }
  }

  // 获取 content 的值（仅用于 outer content）
  const getContentValue = (contentStr) => {
    try {
      const obj = JSON.parse(contentStr)
      return JSON.stringify(obj)
    } catch (error) {
      return '非 JSON 数据'
    }
  }
  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    contentLike: undefined,
    operType: undefined,
    operDeviceType: undefined,
    userId: undefined,
    uTime: [dayjs().startOf('month'), dayjs().endOf('month')], //时间
    uTimeBegin: dayjs().startOf('month').valueOf(), //时间 开始
    uTimeEnd: dayjs().endOf('month').valueOf(), //时间 结束
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  //展开更多查询参数
  const moreQueryConditionFlag = ref(false)
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryForm.pageSize = 10
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await operLogApi.page(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  function onChangeCreateTime(dates) {
    queryForm.uTimeBegin = dates[0].valueOf()
    queryForm.uTimeEnd = dates[1].valueOf()
  }

  const userParams = reactive({
    showRoleFlag: false,
  })
  const filterUserParams = (val) => {
    val.data?.forEach((element, index, arr) => {
      arr[index].disabled = element.status === ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    })
    return val
  }

  onMounted(queryData)
</script>
